<template>
  <el-dialog
    title="导入结果"
    :visible.sync="visible"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="import-result-container">
      <!-- 结果摘要 -->
      <div class="result-summary">
        <div class="summary-item success" v-if="result.successCount > 0">
          <i class="el-icon-success"></i>
          <span class="count">{{ result.successCount }}</span>
          <span class="label">成功</span>
        </div>
        <div class="summary-item failed" v-if="result.failedCount > 0">
          <i class="el-icon-error"></i>
          <span class="count">{{ result.failedCount }}</span>
          <span class="label">失败</span>
        </div>
        <div class="summary-item total">
          <i class="el-icon-document"></i>
          <span class="count">{{ result.totalCount || (result.successCount + result.failedCount) }}</span>
          <span class="label">总计</span>
        </div>
      </div>

      <!-- 失败记录表格 -->
      <div v-if="result.failedRecords && result.failedRecords.length > 0" class="failed-records">
        <h3 class="section-title">
          <i class="el-icon-warning"></i>
          失败记录详情 ({{ result.failedRecords.length }} 条)
        </h3>

        <el-table
          :data="result.failedRecords"
          border
          stripe
          max-height="400"
          style="width: 100%"
        >
          <el-table-column
            prop="row"
            label="行号"
            width="80"
            align="center"
          />
          <el-table-column
            prop="field"
            label="字段"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.field">{{ scope.row.field }}</span>
              <span v-else class="empty-field">-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="value"
            label="值"
            width="150"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span v-if="scope.row.value">{{ scope.row.value }}</span>
              <span v-else class="empty-field">-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="error"
            label="错误信息"
            align="left"
            show-overflow-tooltip
          />
        </el-table>
      </div>

      <!-- 原始消息 -->
      <div class="raw-message" v-if="showRawMessage">
        <h3 class="section-title">
          <i class="el-icon-document-copy"></i>
          原始消息
        </h3>
        <el-input
          type="textarea"
          :value="result.rawMessage"
          :rows="4"
          readonly
        />
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="showRawMessage = !showRawMessage" type="text">
        {{ showRawMessage ? '隐藏' : '显示' }}原始消息
      </el-button>
      <el-button @click="exportFailedRecords" v-if="result.failedRecords && result.failedRecords.length > 0">
        导出失败记录
      </el-button>
      <el-button @click="viewHistory" type="text">
        查看历史记录
      </el-button>
      <el-button type="primary" @click="handleClose">
        确定
      </el-button>
    </div>

    <!-- 历史记录弹窗 -->
    <el-dialog
      title="导入历史记录"
      :visible.sync="historyVisible"
      width="900px"
      append-to-body
    >
      <el-table :data="importHistory" border style="width: 100%">
        <el-table-column prop="timestamp" label="导入时间" width="180" align="center">
          <template slot-scope="scope">
            {{ formatTime(scope.row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="successCount" label="成功" width="80" align="center">
          <template slot-scope="scope">
            <span class="success-count">{{ scope.row.successCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="failedCount" label="失败" width="80" align="center">
          <template slot-scope="scope">
            <span class="failed-count">{{ scope.row.failedCount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalCount" label="总计" width="80" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="viewHistoryDetail(scope.row)"
              :disabled="!scope.row.failedRecords || scope.row.failedRecords.length === 0"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="clearHistory" type="danger" plain>清空历史</el-button>
        <el-button @click="historyVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'ImportResult',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    result: {
      type: Object,
      default: () => ({
        isSuccess: false,
        successCount: 0,
        failedCount: 0,
        failedRecords: [],
        rawMessage: ''
      })
    }
  },
  data() {
    return {
      showRawMessage: false,
      historyVisible: false
    }
  },
  computed: {
    ...mapGetters('importResult', ['importHistory'])
  },
  methods: {
    ...mapActions('importResult', ['clearImportHistory']),

    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    },

    exportFailedRecords() {
      if (!this.result.failedRecords || this.result.failedRecords.length === 0) {
        return
      }

      // 创建CSV内容
      const headers = ['行号', '字段', '值', '错误信息']
      const csvContent = [
        headers.join(','),
        ...this.result.failedRecords.map(record => [
          record.row || '',
          record.field || '',
          record.value || '',
          (record.error || '').replace(/,/g, '，') // 替换逗号避免CSV格式问题
        ].join(','))
      ].join('\n')

      // 下载文件
      const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `导入失败记录_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`
      link.click()
      URL.revokeObjectURL(link.href)
    },

    viewHistory() {
      this.historyVisible = true
    },

    viewHistoryDetail(historyItem) {
      // 创建一个新的结果对象来显示历史详情
      this.$emit('update:result', historyItem)
      this.historyVisible = false
    },

    clearHistory() {
      this.$confirm('确定要清空所有导入历史记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.clearImportHistory()
        this.historyVisible = false
        this.$message.success('历史记录已清空')
      }).catch(() => {})
    },

    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.import-result-container {
  padding: 10px 0;
}

.result-summary {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  gap: 30px;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  min-width: 120px;
}

.summary-item.success {
  background-color: #f0f9ff;
  border: 1px solid #67c23a;
}

.summary-item.failed {
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
}

.summary-item.total {
  background-color: #f4f4f5;
  border: 1px solid #909399;
}

.summary-item i {
  font-size: 24px;
  margin-bottom: 8px;
}

.summary-item.success i {
  color: #67c23a;
}

.summary-item.failed i {
  color: #f56c6c;
}

.summary-item.total i {
  color: #909399;
}

.summary-item .count {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 4px;
}

.summary-item.success .count {
  color: #67c23a;
}

.summary-item.failed .count {
  color: #f56c6c;
}

.summary-item.total .count {
  color: #303133;
}

.summary-item .label {
  font-size: 14px;
  color: #606266;
}

.failed-records {
  margin-top: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.section-title i {
  margin-right: 8px;
  color: #f56c6c;
}

.raw-message {
  margin-top: 20px;
}

.empty-field {
  color: #c0c4cc;
  font-style: italic;
}

.success-count {
  color: #67c23a;
  font-weight: bold;
}

.failed-count {
  color: #f56c6c;
  font-weight: bold;
}

/* 表格样式 */
.el-table {
  margin-top: 10px;
}

.el-table .el-table__header th {
  background-color: #fafafa;
  color: #303133;
  font-weight: bold;
}

.el-table .el-table__row:hover {
  background-color: #f5f7fa;
}
</style>
